package com.yuantu.judiciary.serviceimpl;

import com.google.gson.Gson;
import com.yuantu.judiciary.dao.IQueryEntityDao;
import com.yuantu.judiciary.dao.IQueryRecordDao;
import com.yuantu.judiciary.dao.IQueryResultDao;
import com.yuantu.judiciary.model.api.*;
import com.yuantu.judiciary.model.domain.QueryEntityDO;
import com.yuantu.judiciary.model.domain.QueryRecordDO;
import com.yuantu.judiciary.model.domain.QueryResultDO;
import com.yuantu.judiciary.model.dto.SearchRecordContentDTO;
import com.yuantu.judiciary.model.enums.QueryType;
import com.yuantu.judiciary.model.enums.SearchType;
import com.yuantu.judiciary.service.ICheckResultService;
import com.yuantu.judiciary.service.IOpenApiService;
import com.yuantu.judiciary.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

/**
 * 尽调结果
 *
 * @author syw
 * @since 2023-10-19
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class CheckResultServiceImpl implements ICheckResultService {

    private static final Gson GSON = new Gson();
    private final IOpenApiService apiService;
    private final IQueryResultDao queryResultDao;
    private final IQueryRecordDao queryRecordDao;
    private final IQueryEntityDao queryEntityDao;
    @Value("${upload.file.per.bad}")
    private String uploadPerBadPath;
    @Value("${upload.file.per.dishonest}")
    private String uploadPerDishonestPath;
    @Value("${upload.file.per.limit}")
    private String uploadPerLimitPath;
    @Value("${upload.file.per.business}")
    private String uploadPerBusinessPath;
    @Value("${upload.file.per.judicial}")
    private String uploadPerJudicialPath;
    @Value("${upload.file.ent.basic}")
    private String uploadEntBasicPath;
    @Value("${upload.file.ent.dishonest}")
    private String uploadEntDishonestPath;
    @Value("${upload.file.ent.limit}")
    private String uploadEntLimitPath;
    @Value("${upload.file.ent.judicial}")
    private String uploadEntJudicialPath;
    @Value("${upload.file.per.base}")
    private String uploadPerPath;
    @Value("${upload.file.ent.base}")
    private String uploadEntPath;

    private static final String SLASH = "/";
    private static final String SUFFIX_TXT = ".txt";

    @Override
    public String getJsonData(Long userId, QueryType queryType, SearchRecordContentDTO searchRecord, QueryEntityDO entity) {
        String res = "";

        QueryResultDO queryResult = queryResultDao.findFirstByEntityIdAndTypeAndDeletedFalse(entity.getId(), queryType);

        if (ObjectUtils.isEmpty(queryResult)) {
            try {
                String companyInfoPath;

                if (QueryType.PER_BAD_RECORD.equals(queryType)) {
                    res = apiService.personBadRecord(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1));
                    companyInfoPath = uploadPerBadPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + SUFFIX_TXT;

                } else if (QueryType.PER_DISHONEST.equals(queryType)) {
                    res = apiService.dishonestInfo(new DisHonestInfoDTO(searchRecord.getIdNumber(), searchRecord.getName(), 1));
                    companyInfoPath = uploadPerDishonestPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + SUFFIX_TXT;

                } else if (QueryType.PER_LIMIT.equals(queryType)) {
                    res = apiService.limitHigh(new LimitHighDTO(searchRecord.getIdNumber(), searchRecord.getName(), 1));
                    companyInfoPath = uploadPerLimitPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + SUFFIX_TXT;

                } else if (QueryType.PER_JUDICIAL.equals(queryType)) {
                    res = apiService.judicialInvolvement(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.PERSON));
                    companyInfoPath = uploadPerJudicialPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + SUFFIX_TXT;
                } else if (QueryType.PER_BUSINESS.equals(queryType)) {
                    res = apiService.personBusinessProd(new PersonBadRecordDTO(searchRecord.getIdNumber(), searchRecord.getName(), 1));
                    companyInfoPath = uploadPerBusinessPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + SUFFIX_TXT;

                } else if (QueryType.ENT_BASIC.equals(queryType)) {
                    res = apiService.companyInfo(new CompanyInfoDTO(searchRecord.getName()));
                    companyInfoPath = uploadEntBasicPath + SLASH + searchRecord.getName() + SUFFIX_TXT;

                } else if (QueryType.ENT_DISHONEST.equals(queryType)) {
                    res = apiService.dishonestInfo(new DisHonestInfoDTO(searchRecord.getName(), 1));
                    companyInfoPath = uploadEntDishonestPath + SLASH + searchRecord.getName() + SUFFIX_TXT;

                } else if (QueryType.ENT_LIMIT.equals(queryType)) {
                    res = apiService.limitHigh(new LimitHighDTO(searchRecord.getName(), 1));
                    companyInfoPath = uploadEntLimitPath + SLASH + searchRecord.getName() + SUFFIX_TXT;

                } else if (QueryType.ENT_JUDICIAL.equals(queryType)) {
                    res = apiService.judicialInvolvement(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.ENTERPRISE));
                    companyInfoPath = uploadEntJudicialPath + SLASH + searchRecord.getName() + SUFFIX_TXT;

                } else {
                    return res;
                }

                // 写入文件并上传
                FileUtil.writeToFile(companyInfoPath, res, true);
                QueryResultDO data = new QueryResultDO();
                data.setEntityId(entity.getId());
                data.setResult(companyInfoPath);
                data.setType(queryType);
                data.setCreatorId(userId);
                queryResultDao.save(data);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            // 下载文件json
            res = FileUtil.getTemplateContent(queryResult.getResult());
        }

        return res;
    }

    @Override
    public String getJsonDataProd(Long userId, QueryType queryType, SearchRecordContentDTO searchRecord, QueryEntityDO entity) {
        String res = "";

        QueryResultDO queryResult = queryResultDao.findFirstByEntityIdAndTypeAndDeletedFalse(entity.getId(), queryType);

        if (ObjectUtils.isEmpty(queryResult)) {
            try {
                String companyInfoPath;

                if (QueryType.PER_BAD_RECORD.equals(queryType)) {
                    res = Objects.equals(apiService.personBadRecordProd(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1)), "{}") ? ""
                            : apiService.personBadRecordProd(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1));
                    companyInfoPath = uploadPerPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_bad" + SUFFIX_TXT;

//                } else if (QueryType.PER_DISHONEST.equals(queryType)) {
//                    res = apiService.dishonestInfo(new DisHonestInfoDTO(searchRecord.getIdNumber(), searchRecord.getName(), 1));
//                    companyInfoPath = uploadPerDishonestPath + SLASH + searchRecord.getName() + SUFFIX_TXT;
//
//                } else if (QueryType.PER_LIMIT.equals(queryType)) {
//                    res = apiService.limitHigh(new LimitHighDTO(searchRecord.getIdNumber(), searchRecord.getName(), 1));
//                    companyInfoPath = uploadPerLimitPath + SLASH + searchRecord.getName() + SUFFIX_TXT;
                } else if (QueryType.PER_BUSINESS.equals(queryType)) {
                    res = apiService.personBusinessProd(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1));
                    companyInfoPath = uploadPerBusinessPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_business" + SUFFIX_TXT;
                } else if (QueryType.PER_JUDICIAL.equals(queryType)) {
                    res = Objects.equals(apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.PERSON)), "{}") ? ""
                            : apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.PERSON));
                    companyInfoPath = uploadPerPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_judicial" + SUFFIX_TXT;

                } else if (QueryType.ENT_BASIC.equals(queryType)) {
                    res = Objects.equals(apiService.companyInfoProd(new CompanyInfoDTO(searchRecord.getName())), "{}") ? ""
                            : apiService.companyInfoProd(new CompanyInfoDTO(searchRecord.getName()));
                    companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_basic" + SUFFIX_TXT;

//                } else if (QueryType.ENT_DISHONEST.equals(queryType)) {
//                    res = apiService.dishonestInfo(new DisHonestInfoDTO(searchRecord.getName(), 1));
//                    companyInfoPath = uploadEntDishonestPath + SLASH + searchRecord.getName() + SUFFIX_TXT;
//
//                } else if (QueryType.ENT_LIMIT.equals(queryType)) {
//                    res = apiService.limitHigh(new LimitHighDTO(searchRecord.getName(), 1));
//                    companyInfoPath = uploadEntLimitPath + SLASH + searchRecord.getName() + SUFFIX_TXT;

                } else if (QueryType.ENT_JUDICIAL.equals(queryType)) {
                    res = Objects.equals(apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.ENTERPRISE)), "{}") ? ""
                            : apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.ENTERPRISE));
                    companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_judicial" + SUFFIX_TXT;
                } else if (QueryType.ENT_TAX_BREAK.equals(queryType)) {
                    res = Objects.equals(apiService.enterQueryTaxBreakProd(new CompanyTaxBreakQueryDTO(searchRecord.getCreditCode(),
                            searchRecord.getName(), 1)), "{}") ? ""
                            : apiService.enterQueryTaxBreakProd(new CompanyTaxBreakQueryDTO(searchRecord.getCreditCode(),
                            searchRecord.getName(), 1));
                    companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_tax_break" + SUFFIX_TXT;
                } else if (QueryType.ENT_ADMINISTRATION.equals(queryType)) {
                    res = Objects.equals(apiService.enterQueryAdminPunishProd(new CompanyAdminPunishPageQueryDTO(searchRecord.getName(), 1, 1, 20)), "{}") ? ""
                            : apiService.enterQueryAdminPunishProd(new CompanyAdminPunishPageQueryDTO(searchRecord.getName(), 1, 1, 20));
                    companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_admin_punish" + SUFFIX_TXT;
                } else {
                    return res;
                }
                // 写入文件并上传
                FileUtil.writeToFile(companyInfoPath, res, true);
                QueryResultDO data = new QueryResultDO();
                data.setEntityId(entity.getId());
                data.setResult(companyInfoPath);
                data.setType(queryType);
                data.setCreatorId(userId);
                queryResultDao.save(data);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            // 下载文件json
            res = FileUtil.getTemplateContent(queryResult.getResult());
        }

        return res;
    }

    @Override
    public String updateJsonDataProd(Long userId, QueryType queryType, SearchRecordContentDTO searchRecord, Long entityId) {
        String res = "";

        List<QueryResultDO> queryResult = queryResultDao.findByEntityIdAndTypeAndDeletedFalse(entityId, queryType);
        queryResult.forEach(data -> data.setDeleted(true));
        queryResultDao.saveAll(queryResult);

        try {
            String companyInfoPath;
            if (QueryType.PER_BAD_RECORD.equals(queryType)) {
                res = apiService.personBadRecordProd(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1));
                companyInfoPath = uploadPerPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_bad" + SUFFIX_TXT;

            } else if (QueryType.PER_JUDICIAL.equals(queryType)) {
                res = apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.PERSON));
                companyInfoPath = uploadPerPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_judicial" + SUFFIX_TXT;
            } else if (QueryType.PER_BUSINESS.equals(queryType)) {
                res = apiService.personBusinessProd(new PersonBadRecordDTO(searchRecord.getName(), searchRecord.getIdNumber(), 1));
                companyInfoPath = uploadPerBusinessPath + SLASH + searchRecord.getName() + "_" + searchRecord.getIdNumber() + "_business" + SUFFIX_TXT;

            } else if (QueryType.ENT_BASIC.equals(queryType)) {
                res = apiService.companyInfoProd(new CompanyInfoDTO(searchRecord.getName()));
                companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_basic" + SUFFIX_TXT;

            } else if (QueryType.ENT_JUDICIAL.equals(queryType)) {
                res = apiService.judicialProd(new JudicialInvolvementDTO(searchRecord.getIdNumber(), searchRecord.getName(), "", 1, SearchType.ENTERPRISE));
                companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_judicial" + SUFFIX_TXT;
            } else if (QueryType.ENT_TAX_BREAK.equals(queryType)) {
                res = Objects.equals(apiService.enterQueryTaxBreakProd(new CompanyTaxBreakQueryDTO(searchRecord.getCreditCode(),
                        searchRecord.getName(), 1)), "{}") ? ""
                        : apiService.enterQueryTaxBreakProd(new CompanyTaxBreakQueryDTO(searchRecord.getCreditCode(),
                        searchRecord.getName(), 1));
                companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_tax_break" + SUFFIX_TXT;
            } else if (QueryType.ENT_ADMINISTRATION.equals(queryType)) {
                res = Objects.equals(apiService.enterQueryAdminPunishProd(new CompanyAdminPunishPageQueryDTO(searchRecord.getName(), 1, 1, 10)), "{}") ? ""
                        : apiService.enterQueryAdminPunishProd(new CompanyAdminPunishPageQueryDTO(searchRecord.getName(), 1, 1, 10));
                companyInfoPath = uploadEntPath + SLASH + searchRecord.getName() + "_admin_punish" + SUFFIX_TXT;
            } else {
                return res;
            }

            // 写入文件并上传
            FileUtil.writeToFile(companyInfoPath, res, true);
            QueryResultDO data = new QueryResultDO();
            data.setEntityId(entityId);
            data.setResult(companyInfoPath);
            data.setType(queryType);
            data.setCreatorId(userId);
            queryResultDao.save(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return res;
    }

    @Override
    public QueryEntityDO getQueryEntity(Long accountId, QueryRecordDO queryRecord, SearchRecordContentDTO searchRecord) {
        QueryEntityDO entity;
        if (ObjectUtils.isEmpty(queryRecord.getEntityId())) {
            String code = SearchType.PERSON.equals(queryRecord.getType()) ? searchRecord.getIdNumber() : "";
            entity = queryEntityDao.findByNameAndCodeAndTypeAndCreatorIdAndDeletedFalse(searchRecord.getName(), code, queryRecord.getType(), accountId);
        } else {
            entity = queryEntityDao.findByIdAndDeletedFalse(queryRecord.getEntityId());
        }
        if (ObjectUtils.isEmpty(entity)) {
            String code = SearchType.PERSON.equals(queryRecord.getType()) ? searchRecord.getIdNumber() : "";
            entity = new QueryEntityDO(searchRecord.getName(), code, queryRecord.getType());
            entity.setCreatorId(accountId);
            queryEntityDao.save(entity);
        }
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
            queryRecordDao.save(queryRecord);
        }
        return entity;
    }

}
